package at.com.vn.chess.service;

import at.com.vn.chess.entity.ChatUser;
import at.com.vn.chess.entity.ChessRow;
import vn.com.bip.office.smart.util.XMLHelper;

public class DoChessTableService extends BaseService {

	public DoChessTableService(String inputStrXml) {
		super(inputStrXml);
		logger.info( "Bat dau" );
	}

	@Override
	public void doService() {

		// Create initation xml error message
		String errMessage = "Some error";
		outputStrXml = XMLHelper.convertMessageToXML("DoChessTable", "ERR_MSG",
				"MSG", errMessage);

		if (inputStrXml.trim().equals("")) {
			logger.error( "Client truyen len mot file inputStrXml rong" );
			return;
		}

		// get ChessRow
		ChessRow receiverChessRow = (ChessRow) XMLHelper
				.convertXMLToListObject(inputStrXml, ChessRow.class).get(0);
		String processName = XMLHelper.getProcessName(inputStrXml);

		if (processName.contains("_get_chess_table")) {
			if (chessRowList.size() == 0) {
				receiverChessRow.setTableId(1);
				chessRowList.add(receiverChessRow);
			}
		}
		if (processName.contains("_add_chess_table")) {
			if (chessRowList.size() == 0) {
				receiverChessRow.setTableId(1);
				chessRowList.add(receiverChessRow);
			} else {
				receiverChessRow.setTableId(getMaxChessRowID() + 1);
				chessRowList.add(receiverChessRow);
			}
		}
		if (processName.contains("_click_link_chess_table")
				|| processName.contains("_left")) {
			ChessRow changRow = getChessRowByID(receiverChessRow.getTableId());
			// copy data from Client
			changRow.setCurrentRoomId(receiverChessRow.getCurrentRoomId());
			changRow.setBlackOwner(receiverChessRow.getBlackOwner());
			changRow.setBlackOwnerStatus(receiverChessRow.getBlackOwnerStatus());
			changRow.setWhiteOwner(receiverChessRow.getWhiteOwner());
			changRow.setWhiteOwnerStatus(receiverChessRow.getWhiteOwnerStatus());

			// Set UserChat properties
			ChatUser currentUser = getUserChatByID(changRow.getBlackOwner());
			if (currentUser == null) {
				currentUser = getUserChatByID(changRow.getWhiteOwner());
			}
			if (currentUser != null) {
				currentUser.setPrivateRoomID(receiverChessRow.getTableId());
			}

		}

		// send data
		outputStrXml = XMLHelper.convertListObjectToXML(chessRowList,
				processName, ChessRow.class);

	}

	private ChatUser getUserChatByID(String userID) {
		for (ChatUser iuser : chatUserList) {
			if (iuser.getUserID().equals(userID)) {
				return iuser;
			}
		}
		return null;
	}

	private ChessRow getChessRowByID(int tableID) {
		for (ChessRow irow : chessRowList) {
			if (irow.getTableId() == tableID) {
				return irow;
			}
		}
		return null;
	}

	int getMaxChessRowID() {
		int maxValue = 0;

		for (ChessRow iTable : chessRowList) {
			int value = iTable.getTableId();
			if (value > maxValue) {
				maxValue = value;
			}
		}
		return maxValue;
	}
}